/**
 * 用户认证Store
 * 管理用户登录、注册、登出等认证功能
 * 已改造为使用Django后端API
 */

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import apiClient from '@/api/axios'
import { API_ENDPOINTS } from '@/api/config'

export const useAuthStore = defineStore('auth', () => {
  // ==================== State ====================
  const currentUser = ref(null)
  const isAuthenticated = ref(false)
  const userRole = ref('user')

  // ==================== Getters ====================
  const isAdmin = computed(() => userRole.value === 'admin')
  const isCreator = computed(() => userRole.value === 'creator' || userRole.value === 'admin')
  const userName = computed(() => currentUser.value?.name || 'Guest')
  const userAvatar = computed(() => {
    // 支持多种字段名：avatar_url, avatar, avatarUrl
    if (currentUser.value?.avatar_url) {
      return currentUser.value.avatar_url
    }
    if (currentUser.value?.avatar) {
      return currentUser.value.avatar
    }
    if (currentUser.value?.avatarUrl) {
      return currentUser.value.avatarUrl
    }
    return '/default-avatar.png'
  })

  // ==================== Actions ====================
  
  /**
   * 用户登录
   * @param {string} email - 邮箱
   * @param {string} password - 密码
   * @returns {Promise<Object>} 登录结果
   */
  const login = async (email, password) => {
    try {
      const response = await apiClient.post(API_ENDPOINTS.AUTH_LOGIN, {
        email,
        password
      })
      
      // 适配响应格式
      const data = response.data || response
      const token = data.token || data.access
      const user = data.user || data
      
      // 保存token和用户信息
      localStorage.setItem('token', token)
      localStorage.setItem('user', JSON.stringify(user))
      localStorage.setItem('userRole', user.role || 'user')
      localStorage.setItem('isAuthenticated', 'true')
      
      // 更新store状态
      currentUser.value = user
      userRole.value = user.role || 'user'
      isAuthenticated.value = true
      
      return { success: true, message: response.message || '登录成功' }
    } catch (error) {
      return { 
        success: false, 
        message: error.message || '登录失败，请重试'
      }
    }
  }

  /**
   * 发送邮箱验证码
   * @param {string} email - 邮箱地址
   * @returns {Promise<Object>} 发送结果
   */
  const sendVerificationCode = async (email) => {
    try {
      const response = await apiClient.post(API_ENDPOINTS.AUTH_SEND_CODE, {
        email
      })
      
      return {
        success: true,
        message: response.message || '验证码已发送'
      }
    } catch (error) {
      return {
        success: false,
        message: error.message || '验证码发送失败，请重试'
      }
    }
  }

  /**
   * 邮箱验证码登录
   * @param {string} email - 邮箱
   * @param {string} code - 验证码
   * @returns {Promise<Object>} 登录结果
   */
  const emailCodeLogin = async (email, code) => {
    try {
      const response = await apiClient.post(API_ENDPOINTS.AUTH_EMAIL_LOGIN, {
        email,
        code
      })
      
      // 适配响应格式
      const data = response.data || response
      const token = data.token || data.access
      const user = data.user || data
      
      // 保存token和用户信息
      localStorage.setItem('token', token)
      localStorage.setItem('user', JSON.stringify(user))
      localStorage.setItem('userRole', user.role || 'user')
      localStorage.setItem('isAuthenticated', 'true')
      
      // 更新store状态
      currentUser.value = user
      userRole.value = user.role || 'user'
      isAuthenticated.value = true
      
      return { success: true, message: response.message || '登录成功' }
    } catch (error) {
      return { 
        success: false, 
        message: error.message || '登录失败，请重试'
      }
    }
  }

  /**
   * 重置密码
   * @param {string} email - 邮箱
   * @param {string} code - 验证码
   * @param {string} newPassword - 新密码
   * @param {string} confirmPassword - 确认密码
   * @returns {Promise<Object>} 重置结果
   */
  const resetPassword = async (email, code, newPassword, confirmPassword) => {
    try {
      const response = await apiClient.post(API_ENDPOINTS.AUTH_RESET_PASSWORD, {
        email,
        code,
        new_password: newPassword,
        confirm_password: confirmPassword
      })
      
      return {
        success: true,
        message: response.message || '密码重置成功'
      }
    } catch (error) {
      return {
        success: false,
        message: error.message || '密码重置失败，请重试'
      }
    }
  }

  /**
   * 用户注册
   * @param {Object} userData - 注册数据
   * @returns {Promise<Object>} 注册结果
   */
  const register = async (userData) => {
    try {
      const { name, email, password, confirmPassword } = userData
      
      const response = await apiClient.post(API_ENDPOINTS.AUTH_REGISTER, {
        name,
        email,
        password,
        confirm_password: confirmPassword
      })
      
      return {
        success: true,
        message: response.message || '注册成功'
      }
    } catch (error) {
      return {
        success: false,
        message: error.message || '注册失败，请重试'
      }
    }
  }

  /**
   * 用户登出
   */
  const logout = async () => {
    try {
      await apiClient.post(API_ENDPOINTS.AUTH_LOGOUT)
    } catch (error) {
      console.error('登出失败:', error)
    } finally {
      // 无论是否成功，都清除本地数据
      currentUser.value = null
      isAuthenticated.value = false
      userRole.value = 'user'
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      localStorage.removeItem('userRole')
      localStorage.removeItem('isAuthenticated')
    }
  }

  /**
   * 更新用户资料
   * @param {Object|FormData} profileData - 要更新的资料
   */
  const updateProfile = async (profileData) => {
    try {
      if (!currentUser.value) {
        throw new Error('用户未登录')
      }
      
      console.log('开始更新用户资料...')
      console.log('当前用户ID:', currentUser.value.id)
      console.log('更新数据类型:', profileData instanceof FormData ? 'FormData' : 'Object')
      
      // 使用Django标准的profile更新接口
      const response = await apiClient.put(
        API_ENDPOINTS.USER_UPDATE_PROFILE,
        profileData
      )
      
      console.log('更新响应:', response)
      
      // 适配响应格式
      const userData = response.data || response
      
      // 更新当前用户信息（使用后端返回的完整数据）
      currentUser.value = {
        ...currentUser.value,
        ...userData,
        // 确保头像URL正确
        avatar: userData.avatar || userData.avatar_url || currentUser.value.avatar,
        avatar_url: userData.avatar_url || userData.avatar || currentUser.value.avatar_url
      }
      
      // 保存到localStorage，确保刷新后数据不丢失
      localStorage.setItem('user', JSON.stringify(currentUser.value))
      
      console.log('用户资料更新成功:', currentUser.value)
      console.log('头像URL:', currentUser.value.avatar)
      
      return response
    } catch (error) {
      console.error('更新用户资料失败:', error)
      console.error('错误详情:', error.response?.data)
      throw error
    }
  }

  /**
   * 修改密码
   * @param {Object} passwordData - 密码数据
   */
  const changePassword = async (passwordData) => {
    try {
      if (!currentUser.value) return
      
      const response = await apiClient.post(
        API_ENDPOINTS.USER_CHANGE_PASSWORD(currentUser.value.id),
        {
          old_password: passwordData.oldPassword,
          new_password: passwordData.newPassword,
          confirm_password: passwordData.confirmPassword
        }
      )
      
      return response
    } catch (error) {
      throw error
    }
  }

  /**
   * 初始化认证状态
   * 从localStorage恢复用户信息并验证token
   */
  const initializeAuth = async () => {
    const savedUser = localStorage.getItem('user')
    const savedAuth = localStorage.getItem('isAuthenticated')
    const token = localStorage.getItem('token')
    
    if (savedUser && savedAuth === 'true' && token) {
      try {
        // 验证token是否有效
        const response = await apiClient.get(API_ENDPOINTS.AUTH_ME)
        
        // 适配响应格式
        const userData = response.data || response
        currentUser.value = userData
        userRole.value = userData.role || 'user'
        isAuthenticated.value = true
        
        console.log('用户认证初始化成功:', userData)
      } catch (error) {
        // token验证失败，清除本地数据
        console.log('Token验证失败，清除本地数据')
        logout()
      }
    }
  }

  // ==================== Return ====================
  return {
    // State
    currentUser,
    isAuthenticated,
    userRole,
    
    // Getters
    isAdmin,
    isCreator,
    userName,
    userAvatar,
    
    // Actions
    login,
    sendVerificationCode,
    emailCodeLogin,
    resetPassword,
    register,
    logout,
    updateProfile,
    changePassword,
    initializeAuth
  }
})
